from tkinter import *#库自带
import win32gui #pip install pywin32
from pywinauto import application#pip install pywinauto
 
class command:
    def __init__(self):
        self.hwnd_title = dict()
        
    def get_all_hwnd(self,hwnd,mouse):
        if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
            self.hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})  
                   
    def handle_find(self):#查找句柄
        win32gui.EnumWindows(self.get_all_hwnd, 0)
        for h,t in self.hwnd_title.items():
            if t is not "":
                print(t,h)#其中t为标题，h为句柄数值
                
    def control_find(self):#查找控件信息
        title=self.lo.get()
        app=application.Application().connect(title_re=title)
        window_title=[title]
        app[window_title].print_control_identifiers(filename=r"C:\\L\\1.txt")
 
class main(command):
    def interface(self):
        root = Tk() 
        root.title("句柄与控件查找")   
        root.geometry("400x250")    
        root.resizable(width=False, height=False) 
        fm1=Frame(root)
        Button(fm1,text='句柄查找',font=('Arial', 12),command=self.handle_find,activeforeground="white",activebackground='gray',bg='white',fg='black',width=10,wraplength=100).pack(side=LEFT,padx=10)
        self.lo=Entry(fm1, show=None, font=('Arial', 14),width=15)
        self.lo.insert(0, '请输入标题')
        self.lo.pack(side=LEFT,padx=10)
        fm1.pack(side=TOP,pady=30)
        fm1=Frame(root)
        Button(fm1,text='控件查找',font=('Arial', 12),command=self.control_find,activeforeground="white",activebackground='gray',bg='white',fg='black',width=10,wraplength=100).pack(side=LEFT,padx=10)
        Label(fm1, text=" ", bd=1, font=("Arial",12), width=20, height=1).pack(side=LEFT)
        fm1.pack(side=TOP)
        root.mainloop()
 
if __name__ == '__main__':
    main().interface()